package com.lzb.watermarkcamera.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.watermarkcamera.BaseEditFragment;
import com.lzb.watermarkcamera.R;
import com.lzb.watermarkcamera.activity.PicEditActivity;
import com.lzb.watermarkcamera.adapter.TextColorAdapter;
import com.lzb.watermarkcamera.basic.imgedit.Matrix3;
import com.lzb.watermarkcamera.basic.imgedit.TextStickerView;
import com.lzb.watermarkcamera.basic.utils.RxUtil;
import com.lzb.watermarkcamera.bean.ColorBean;
import com.lzb.watermarkcamera.databinding.FragmentAddTextBinding;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddTextFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddTextFragment extends BaseEditFragment<FragmentAddTextBinding> implements View.OnClickListener, OnItemClickListener {

    public static final int INDEX = 5;

    private TextStickerView mTextStickerView;
    private int mTextColor = Color.WHITE;
    private InputMethodManager imm;
    private TextColorAdapter colorAdapter;
    private int oldPosition = 0;

    public static AddTextFragment newInstance() {
        AddTextFragment fragment = new AddTextFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        mImgEditActivity.mode = PicEditActivity.MODE_TEXT;
        mImgEditActivity.mImgView.setImageBitmap(mImgEditActivity.getMainBit());
        mTextStickerView.setVisibility(View.VISIBLE);
        mDataBinding.etInput.clearFocus();
    }

    @Override
    public void backToMain() {
        hideInput();
        mImgEditActivity.mode = PicEditActivity.MODE_NONE;
        mImgEditActivity.mImgView.setVisibility(View.VISIBLE);
        mTextStickerView.setVisibility(View.GONE);
        mImgEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_add_text;
    }

    @Override
    protected void initView() {
        mDataBinding.ivApply.setOnClickListener(this);

        oldPosition = 0;
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mTextStickerView = mImgEditActivity.mTextStickerView;
        mTextStickerView.setEditText(mDataBinding.etInput);
        LinearLayoutManager stickerListLayoutManager = new LinearLayoutManager(mImgEditActivity);
        stickerListLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        mDataBinding.rvColor.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new TextColorAdapter();
        mDataBinding.rvColor.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
        onShow();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivApply) {//确定
            String text = mDataBinding.etInput.getText().toString();
            if (TextUtils.isEmpty(text)) {
                ToastUtils.showShort(getString(R.string.please_input_text));
                return;
            }
            mTextStickerView.setText(text);
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelected(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        colorAdapter.getItem(position).setSelected(true);
        colorAdapter.notifyItemChanged(position);

        mTextStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        List<ColorBean> listColor = new ArrayList<>();
        listColor.add(new ColorBean("#000000", true));
        listColor.add(new ColorBean("#FFFFFF", false));
        listColor.add(new ColorBean("#FF0000", false));
        listColor.add(new ColorBean("#FFA600", false));
        listColor.add(new ColorBean("#FAFD00", false));
        listColor.add(new ColorBean("#13FD00", false));
        listColor.add(new ColorBean("#00F5FF", false));
        listColor.add(new ColorBean("#295EFF", false));
        listColor.add(new ColorBean("#295EFF", false));
        colorAdapter.setList(listColor);
        mTextStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(0).getColor()));
    }

    public void hideInput() {
        if (getActivity() != null && getActivity().getCurrentFocus() != null && isInputMethodShow()) {
            imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isInputMethodShow() {
        return imm.isActive();
    }

    /**
     * 保存文字图片
     */
    public void applyTextImage() {
        showDialog(getString(R.string.handle_ing));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Matrix touchMatrix = mImgEditActivity.mImgView.getImageViewMatrix();
                Bitmap retBitmap = Bitmap.createBitmap(mImgEditActivity.getMainBit()).copy(
                        Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);

                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());

                float[] f = new float[9];
                m.getValues(f);
                int dx = (int) f[Matrix.MTRANS_X];
                int dy = (int) f[Matrix.MTRANS_Y];
                float scale_x = f[Matrix.MSCALE_X];
                float scale_y = f[Matrix.MSCALE_Y];
                canvas.save();
                canvas.translate(dx, dy);
                canvas.scale(scale_x, scale_y);
                mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                        mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
                canvas.restore();
                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                mTextStickerView.clearTextContent();
                mTextStickerView.resetView();

                mImgEditActivity.changeMainBitmap(bitmap, true);
                backToMain();
            }
        });
    }

}